package cn.xiaolang.function.network.io;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
import java.util.LinkedList;

/**
 * http://www.kegel.com/c10k.html
 *
 * @author Dean
 * @date 2022-01-26
 */
public class C10kClient {

    public static void main(String[] args) {
        LinkedList<SocketChannel> clients = new LinkedList<>();
        InetSocketAddress serverSocket = new InetSocketAddress("127.0.0.1", 10010);


        for (int i = 10020; i < 65000; i++) {
            try {
                SocketChannel client1 = SocketChannel.open();
                client1.bind(new InetSocketAddress("127.0.0.1", i));
                client1.connect(serverSocket);
                boolean c1ConnResult = client1.isConnected();
                System.out.println(client1.socket().getLocalSocketAddress().toString() + " connected: " + c1ConnResult);
                clients.add(client1);

//                SocketChannel client2 = SocketChannel.open();
//                client2.bind(new InetSocketAddress("10.10.206.106", i));
//                client2.connect(serverSocket);
//                boolean c2ConnResult = client2.isConnected();
//                System.out.println(client1.socket().getRemoteSocketAddress().toString() + "connected" + c2ConnResult);
//                clients.add(client2);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        System.out.println("clients:" + clients.size());

        try {
            // blocking
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
